<template>
	<el-dialog :title="!dataForm.roleId ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
		<el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
			label-width="80px">
			<el-form-item label="角色">
				<el-select v-model="dataForm.roleId" @change="init(dataForm.roleId)" placeholder="请选择">
					<el-option v-for="item in options" :key="item.id" :label="item.role" :value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-transfer v-model="dataForm.permissionIds" :titles="titles" :data="permissionList"
					@change="change"></el-transfer>
			</el-form-item>
		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="cancle()">取消</el-button>
			<el-button type="primary" @click="dataFormSubmit()">确定</el-button>
		</span>
	</el-dialog>
</template>

<script>
	export default {
		data() {
			return {
				previousSelection: [], // 先前选中的项
				currentSelection: [], // 当前选中的项
				options: [],
				permissionList: [],
				titles: ['所有权限', '已选权限'],
				value: [],
				disabled: true,
				visible: false,
				dataForm: {
					roleId: 0,
					permissionIds: [],
					addedIds: [],
					removedIds: []
				},
				dataRule: {
					permissionId: [{
						required: true,
						message: '权限id不能为空',
						trigger: 'blur'
					}],
					createTime: [{
						required: true,
						message: '创建时间不能为空',
						trigger: 'blur'
					}],
					modifyTime: [{
						required: true,
						message: '修改时间不能为空',
						trigger: 'blur'
					}]
				}
			}
		},
		created() {
			this.getOptions();
			this.getPermissionList()
		},
		methods: {
			change(value, direction, movedKeys) {
				console.log('permissionIds:', this.dataForm.permissionIds)
				console.log('value:', value);
				console.log('direction:', direction);
				console.log('movedKeys:', movedKeys);

				// 更新先前选中的项和当前选中的项
				this.previousSelection = this.previousSelection;
				this.currentSelection = value;

				// 计算 addedIds（从先前选中的项中排除当前选中的项）
				const addedIds = this.currentSelection.filter(item => !this.previousSelection.includes(item));

				// 计算 removedIds（从当前选中的项中排除先前选中的项）
				const removedIds = this.previousSelection.filter(item => !this.currentSelection.includes(item));

				this.dataForm.addedIds = addedIds
				this.dataForm.removedIds = removedIds
			},
			getOptions() {
				this.$http.post('/role/getRoleList').then(({
					data
				}) => {
					if (data.code === 200) {
						this.options = data.options
					}
				})
			},
			getPermissionList() {
				this.$http.post('/permission/getPermissionList').then(({
					data
				}) => {
					if (data.code === 200) {
						let permissionList = []
						for (let one of data.permissionList) {
							permissionList.push({
								key: one.id,
								label: one.desc
							})
						}
						this.permissionList = permissionList
					}
				})
			},
			init(id) {
				this.dataForm.roleId = id || null
				this.visible = true
				this.$nextTick(() => {
					this.$refs['dataForm'].resetFields()
					if (this.dataForm.roleId) {
						this.$http.post('/role_permission/searchRolePermissionInfo', {
							roleId: this.dataForm.roleId
						}).then(({
							data
						}) => {
							if (data.data != null) {
								this.dataForm.permissionIds = JSON.parse(data.data.permissionIds)
								this.previousSelection = JSON.parse(data.data.permissionIds)
							} else {
								this.dataForm.permissionIds = []
								this.previousSelection = []
							}
						})
					}
				})
			},
			// 表单提交
			dataFormSubmit() {
				this.$refs['dataForm'].validate((valid) => {
					if (valid) {
						this.$http.post('role_permission/update', {
							roleId: this.dataForm.roleId,
							addedIds: this.dataForm.addedIds,
							removedIds: this.dataForm.removedIds
						}).then(({
							data
						}) => {
							if (data.code == 200) {
								this.$message({
									message: '操作成功',
									type: 'success',
									duration: 1200
								})
								this.visible = false;
								this.$emit('refreshDataList')
							}
						})
						// this.$http({
						// 	url: this.$http.adornUrl(
						// 		`/mall/rolepermission/${!this.dataForm.roleId ? 'save' : 'update'}`),
						// 	method: 'post',
						// 	data: this.$http.adornData({
						// 		'roleId': this.dataForm.roleId || undefined,
						// 		'permissionId': this.dataForm.permissionId,
						// 		'createTime': this.dataForm.createTime,
						// 		'modifyTime': this.dataForm.modifyTime
						// 	})
						// }).then(({
						// 	data
						// }) => {
						// 	if (data && data.code === 0) {
						// 		this.$message({
						// 			message: '操作成功',
						// 			type: 'success',
						// 			duration: 1500,
						// 			onClose: () => {
						// 				this.visible = false
						// 				this.$emit('refreshDataList')
						// 			}
						// 		})
						// 	} else {
						// 		this.$message.error(data.msg)
						// 	}
						// })
					}
				})
			},
			cancle() {
				this.visible = false;
				this.dataForm.roleId = null
				this.dataForm.permissionIds = []
				this.$refs['dataForm'].resetFields();
				this.previousSelection = []
				this.currentSelection = []
			}
		}
	}
</script>